package sy.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.dao.Dao;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ForwardView;
import org.nutz.mvc.view.UTF8JsonView;

import sy.bo.JsonResult;
import sy.po.Company;

/**
 * 
 * 验证session中是否有name信息，并且name不为空
 * 
 * 忽略路由是"/global/"开头的方法
 * 
 * @author 孙宇
 *
 */
public class SessionFilter implements ActionFilter {

	private String name;

	public SessionFilter(String name) {
		this.name = name;
	}

	@Override
	public View match(ActionContext actionContext) {
		HttpServletRequest request = Mvcs.getReq();
		String requestPath = Mvcs.getRequestPath(request);
		if (requestPath.startsWith("/global/")) {// 忽略路由是/global/开头的方法，跳过验证
			return null;
		}
		HttpSession session = Mvcs.getHttpSession(false);
		if (session == null || null == session.getAttribute(name)) {
			if (request.getHeader("X-Requested-With") == null) {// 如果不是ajax请求，就返回登录页
				request.setAttribute("companys", actionContext.getIoc().get(Dao.class).query(Company.class, null));// 由于登录页面需要公司列表，所以先查询出来，放到request中，便于login.jsp获取
				return new ForwardView("/WEB-INF/jsp/login.jsp");
			} else {// 是ajax请求，返回json格式的信息
				UTF8JsonView view = new UTF8JsonView(null);
				view.setData(new JsonResult(false, "登录超时或未登录，请重新登录！"));
				return view;
			}
		}
		return null;
	}

}
